<template>
  <div
    class="affix fixed right-0 bottom-[8vh] duration-300"
    :class="{ visible }"
  >
    <ul>
      <nuxt-link
        :to="switchLocalePath(language === 'en' ? 'zh_cn' : 'en')"
        class="group block mb-1"
      >
        <div
          class="text-base cursor-pointer w-[30px] h-[30px] text-white bg-[#49b1f5] flex justify-center items-center group-hover:bg-[#ff7242] duration-300"
        >
          <svg-icon v-if="language === 'en'" icon-class="zhongwen" />
          <svg-icon v-else icon-class="Aa" />
        </div>
      </nuxt-link>

      <li class="group mb-1" @click="handleChangeTheme">
        <div
          class="text-base cursor-pointer w-[30px] h-[30px] text-white bg-[#49b1f5] flex justify-center items-center group-hover:bg-[#ff7242] duration-300"
        >
          <svg-icon v-if="theme === 'dark'" icon-class="yueliang" />
          <svg-icon v-else icon-class="taiyang" />
        </div>
      </li>

      <li class="group" @click="handleScrollTop">
        <div
          class="text-base cursor-pointer w-[30px] h-[30px] text-white bg-[#49b1f5] flex justify-center items-center group-hover:bg-[#ff7242] duration-300"
        >
          <svg-icon icon-class="arrow-up" />
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import gsap from 'gsap'
import { mapMutations, mapState } from 'vuex'
// 临界值
const CRITICAL_VALUE = 200
export default {
  data() {
    const language = this.$i18n.locale
    return {
      visible: false,
      language,
    }
  },
  computed: {
    ...mapState({
      theme: (state) => state.app.theme,
    }),
  },
  watch: {
    $route: {
      handler() {
        this.language = this.$i18n.locale
      },
      immediate: true,
    },
  },
  mounted() {
    this.watchScroll()
  },

  methods: {
    ...mapMutations({
      SET_THEME: 'app/SET_THEME',
    }),
    watchScroll() {
      const handleScroll = () => {
        const scrollTop = document.documentElement.scrollTop
        if (scrollTop > CRITICAL_VALUE) {
          this.visible = true
        } else {
          this.visible = false
        }
      }
      window.addEventListener('scroll', handleScroll)
      this.$on('hook:beforeDestory', () => {
        window.removeEventListener('scroll', handleScroll)
      })
      //   初始化时执行一次
      handleScroll()
    },
    // 滚动到顶部
    handleScrollTop() {
      gsap.to(document.documentElement, {
        scrollTop: 0,
        duration: 0.5,
        ease: 'power2.out',
      })
    },
    // 切换主题
    handleChangeTheme() {
      this.SET_THEME(this.theme === 'dark' ? 'light' : 'dark')
    },
  },
}
</script>

<style lang="scss" scoped>
.affix {
  transform: translateX(100%);
  opacity: 0;
  &.visible {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>
